// 创建一个路由器，并暴露出去
import { createRouter, createWebHashHistory } from 'vue-router'

const router = createRouter({
  history: createWebHashHistory(import.meta.env.BASE_URL),
  routes: [//配置路由规则
    { //主页
      path: '/',
      name: '主页',
      component: () => import('@/views/index/index.vue'),
      redirect: '/index',   // 重定向到后台管理
      children: [
        {
          path: 'index',
          name: '首页',
          component: () => import('@/views/index/index.vue')
        },
      ]
    },
    { //登录页
      path: '/login',
      name: 'login',
      component: () => import('@/views/Login.vue')
    },
    { // 后台管理
      path: '/admin',
      name: '后台管理',
      component: () => import('@/layout/index.vue'),
      meta: { requiresAuth: true, title: '后台管理' },
      redirect: '/admin/workSpace/console',
      children: [
        // 工作空间
        {
          path: 'workSpace/console',
          name: '控制台',
          component: () => import('@/views/workSpace/console/index.vue')
        },
        {
          path: 'workSpace/monitor',
          name: '监控页',
          component: () => import('@/views/workSpace/monitor/index.vue')
        },
        // 数据管理
        {
          path: 'dataManage/tree',
          name: '样木管理',
          component: () => import('../views/dataManage/tree/index.vue')
        },
        {
          path: 'dataManage/treedia',
          name: '样木直径',
          component: () => import('../views/dataManage/treeDia/index.vue')
        },
        {
          path: 'dataManage/treefw',
          name: '器官鲜重',
          component: () => import('../views/dataManage/treeFW/index.vue')
        },
        {
          path: 'dataManage/treedw',
          name: '干生物量',
          component: () => import('../views/dataManage/treeDW/index.vue')
        },
        {
          path: 'dataManage/treeSample',
          name: '样品记录',
          component: () => import('../views/dataManage/treeSample/index.vue')
        },
        {
          path: 'dataManage/totals',
          name: '数据汇总',
          component: () => import('../views/dataManage/totals/index.vue')
        },
        // 字段维护
        {
          path: 'field/treeSpecies',
          name: '树种管理',
          component: () => import('../views/field/treeSpecies/index.vue')
        },
        {
          path: 'field/sampleArea',
          name: '样地管理',
          component: () => import('../views/field/sampleArea/index.vue')
        },
        // 系统管理
        {
          path: 'system/user',
          name: '用户管理',
          component: () => import('../views/system/user/index.vue')
        },
        {
          path: 'system/role',
          name: '角色管理',
          component: () => import('../views/system/role/index.vue')
        },
        {
          path: 'system/menu',
          name: '菜单管理',
          component: () => import('../views/system/menu/index.vue')
        },
        {
          path: 'system/icons',
          name: '图标库',
          component: () => import('../views/system/icons/index.vue')
        },
        // 业务管理
        {
          path: 'bsns/department',
          name: '部门管理',
          component: () => import('../views/bsns/Department.vue')
        },
        {
          path: 'bsns/post',
          name: '岗位管理',
          component: () => import('../views/bsns/Post.vue')
        },

        // // 个人中心
        // {
        //   path: 'userCenter',
        //   name: '个人中心',
        //   component: () => import('../views/sys/userCenter/index')
        // },
      ]
    },

    { // 出错页面
      path: '/error',
      children: [
        { path: '401', component: () => import('@/views/error/401.vue') },
        { path: '403', component: () => import('@/views/error/403.vue') },
        { path: '404', component: () => import('@/views/error/404.vue') },
        { path: '500', component: () => import('@/views/error/500.vue') }
      ]
    },

    { // 捕获所有未匹配的路由
      path: '/:pathMatch(.*)*',
      redirect: '/error/404'
    }
  ],
})

// 设置路由守卫
router.beforeEach(async (to, from, next) => {
  const requiresAuth = to.matched.some(record => record.meta.requiresAuth);
  if (requiresAuth) {
    try {
      // 动态导入 Pinia store，确保在应用初始化后使用
      // const { useUserStore } = await import('@/store/user');
      // const { loginUser } = useUserStore();

      // 检查用户是否登录
      const token = window.sessionStorage.getItem('token');
      if (!token) {
        console.log("用户未登录，跳转登录页!");
        next('/login');
      } else {
        // 检查用户是否有权限访问该路由
        const menuList = JSON.parse(window.sessionStorage.getItem('menuList') || '[]');
        const pathList = ['/admin/userCenter']; // 个人中心所有用户都可以访问
        for (let item of menuList) {
          pathList.push(item.path);
          if (item.children && item.children.length > 0) {
            for (let child of item.children) {
              pathList.push(child.path);
            }
          }
        }
        if (!pathList.includes(to.path)) {
          console.log("没有访问权限，跳转403页面!");
          return next('/error/403');
        } else {
          next();
        }
      }
    } catch (error) {
      console.error('store 访问错误:', error);
      next('/login');
    }
  } else {
    next();
  }
});

// 第四步：暴露路由器router
export default router
